<template>
    <div class="book-management-container">
      <el-card shadow="never" class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="图书名称">
            <el-input v-model="searchForm.title" placeholder="请输入图书名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="图书作者">
            <el-input v-model="searchForm.author" placeholder="请输入作者" clearable></el-input>
          </el-form-item>
          <el-form-item label="图书分类">
            <el-select v-model="searchForm.category" placeholder="请选择分类" clearable>
              <el-option label="计算机" value="computer"></el-option>
              <el-option label="文学" value="literature"></el-option>
              <el-option label="历史" value="history"></el-option>
              <el-option label="科学" value="science"></el-option>
              <el-option label="经济" value="economics"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <el-card shadow="never" class="table-card">
        <div class="table-header">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 新增图书
          </el-button>
          <el-button :disabled="!selectedRows.length" @click="handleBatchDelete">
            <i class="el-icon-delete"></i> 批量删除
          </el-button>
          <el-button @click="handleExport">
            <i class="el-icon-download"></i> 导出数据
          </el-button>
        </div>
  
        <el-table
          :data="bookList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="cover" label="封面" width="100">
            <template slot-scope="scope">
              <el-image
                style="width: 60px; height: 80px"
                :src="scope.row.cover"
                fit="contain"
                :preview-src-list="[scope.row.cover]"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="图书名称"></el-table-column>
          <el-table-column prop="author" label="作者"></el-table-column>
          <el-table-column prop="isbn" label="ISBN" width="180"></el-table-column>
          <el-table-column prop="category" label="分类">
            <template slot-scope="scope">
              <el-tag>{{ formatCategory(scope.row.category) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === '在馆' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="总数" width="80"></el-table-column>
          <el-table-column prop="available" label="可借" width="80"></el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <div class="pagination-container">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pagination.currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
          ></el-pagination>
        </div>
      </el-card>
  
      <!-- 新增/编辑图书对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="bookForm" :rules="rules" ref="bookForm" label-width="100px">
          <el-form-item label="图书名称" prop="title">
            <el-input v-model="bookForm.title" placeholder="请输入图书名称"></el-input>
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="bookForm.author" placeholder="请输入作者"></el-input>
          </el-form-item>
          <el-form-item label="ISBN" prop="isbn">
            <el-input v-model="bookForm.isbn" placeholder="请输入ISBN"></el-input>
          </el-form-item>
          <el-form-item label="分类" prop="category">
            <el-select v-model="bookForm.category" placeholder="请选择分类" style="width: 100%">
              <el-option label="计算机" value="computer"></el-option>
              <el-option label="文学" value="literature"></el-option>
              <el-option label="历史" value="history"></el-option>
              <el-option label="科学" value="science"></el-option>
              <el-option label="经济" value="economics"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <el-upload
              class="avatar-uploader"
              action="https://jsonplaceholder.typicode.com/posts/"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="bookForm.cover" :src="bookForm.cover" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="总数" prop="total">
            <el-input-number v-model="bookForm.total" :min="1" :max="1000"></el-input-number>
          </el-form-item>
          <el-form-item label="简介" prop="description">
            <el-input type="textarea" v-model="bookForm.description" :rows="3"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  export default {
    name: "BookManagement",
    data() {
      return {
        searchForm: {
          title: "",
          author: "",
          category: ""
        },
        bookList: [],
        selectedRows: [],
        loading: false,
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        dialogVisible: false,
        dialogTitle: "",
        isAdd: false,
        bookForm: {
          id: "",
          title: "",
          author: "",
          isbn: "",
          category: "computer",
          cover: "",
          total: 1,
          available: 1,
          status: "在馆",
          description: ""
        },
        rules: {
          title: [
            { required: true, message: "请输入图书名称", trigger: "blur" }
          ],
          author: [
            { required: true, message: "请输入作者", trigger: "blur" }
          ],
          isbn: [
            { required: true, message: "请输入ISBN", trigger: "blur" }
          ],
          category: [
            { required: true, message: "请选择分类", trigger: "change" }
          ],
          total: [
            { required: true, message: "请输入总数", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.fetchBookList();
    },
    methods: {
      fetchBookList() {
        this.loading = true;
        // 模拟API请求
        setTimeout(() => {
          this.bookList = [
            {
              id: 1,
              title: "Vue.js设计与实现",
              author: "霍春阳",
              isbn: "9787115583864",
              category: "computer",
              cover: "https://img9.doubanio.com/view/subject/s/public/s34200205.jpg",
              total: 10,
              available: 8,
              status: "在馆",
              description: "深入解析Vue.js实现原理"
            },
            {
              id: 2,
              title: "JavaScript高级程序设计",
              author: "尼古拉斯·泽卡斯",
              isbn: "9787115275790",
              category: "computer",
              cover: "https://img9.doubanio.com/view/subject/s/public/s8958650.jpg",
              total: 5,
              available: 0,
              status: "借出",
              description: "JavaScript经典著作"
            },
            {
              id: 3,
              title: "人类简史",
              author: "尤瓦尔·赫拉利",
              isbn: "9787508647357",
              category: "history",
              cover: "https://img9.doubanio.com/view/subject/s/public/s27814883.jpg",
              total: 8,
              available: 6,
              status: "在馆",
              description: "从动物到上帝的人类发展史"
            }
          ];
          this.pagination.total = 3;
          this.loading = false;
        }, 500);
      },
      formatCategory(category) {
        const map = {
          computer: "计算机",
          literature: "文学",
          history: "历史",
          science: "科学",
          economics: "经济"
        };
        return map[category] || category;
      },
      handleSearch() {
        this.pagination.currentPage = 1;
        this.fetchBookList();
      },
      resetSearch() {
        this.searchForm = {
          title: "",
          author: "",
          category: ""
        };
        this.handleSearch();
      },
      handleSelectionChange(val) {
        this.selectedRows = val;
      },
      handleSizeChange(val) {
        this.pagination.pageSize = val;
        this.fetchBookList();
      },
      handleCurrentChange(val) {
        this.pagination.currentPage = val;
        this.fetchBookList();
      },
      handleAdd() {
        this.dialogTitle = "新增图书";
        this.isAdd = true;
        this.bookForm = {
          id: "",
          title: "",
          author: "",
          isbn: "",
          category: "computer",
          cover: "",
          total: 1,
          available: 1,
          status: "在馆",
          description: ""
        };
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.bookForm.clearValidate();
        });
      },
      handleEdit(row) {
        this.dialogTitle = "编辑图书";
        this.isAdd = false;
        this.bookForm = Object.assign({}, row);
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.bookForm.clearValidate();
        });
      },
      handleDelete(row) {
        this.$confirm(`确定删除图书 "${row.title}" 吗?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // 这里添加删除逻辑
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.fetchBookList();
        });
      },
      handleBatchDelete() {
        const titles = this.selectedRows.map(item => item.title).join(", ");
        this.$confirm(`确定删除选中的 ${this.selectedRows.length} 本图书吗?<br>${titles}`, "提示", {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          // 这里添加批量删除逻辑
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.fetchBookList();
        });
      },
      handleExport() {
        this.$message({
          type: "success",
          message: "导出成功!"
        });
      },
      handleAvatarSuccess(res, file) {
        this.bookForm.cover = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
  
        if (!isJPG && !isPNG) {
          this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        return (isJPG || isPNG) && isLt2M;
      },
      submitForm() {
        this.$refs.bookForm.validate(valid => {
          if (valid) {
            // 这里添加提交逻辑
            this.$message({
              type: "success",
              message: this.isAdd ? "新增成功!" : "修改成功!"
            });
            this.dialogVisible = false;
            this.fetchBookList();
          } else {
            return false;
          }
        });
      }
    }
  };
  </script>
  
  <style lang="less" scoped>
  .book-management-container {
    padding: 20px;
  
    .search-card {
      margin-bottom: 20px;
  
      .search-form {
        display: flex;
        flex-wrap: wrap;
      }
    }
  
    .table-card {
      .table-header {
        margin-bottom: 15px;
        display: flex;
        align-items: center;
  
        .el-button {
          margin-right: 10px;
        }
      }
    }
  
    .pagination-container {
      margin-top: 15px;
      text-align: right;
    }
  }
  
  .avatar-uploader {
    ::v-deep .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
  
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
  
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
  }
  </style>